package com.atguigu.config;

import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:hx
 * @DateTime:2022/10/4 20:50
 * @Description:
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @DubboReference
    private AdminService adminService;
    @DubboReference
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        Admin admin = adminService.getAdminByUsername(username);
        if (admin == null){
            return null;
        }
        //查询用户所拥有的权限
        List<String> permissionList = permissionService.findPermissionCodeListByAdminId(admin.getId());
        //声明用户权限集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        //授权
        for (String permission : permissionList) {
            if (StringUtils.isEmpty(permission)){
                continue;
            }
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        return new User(admin.getUsername(),admin.getPassword(),authorities);
    }
}
